package io.github.frailty9.crserver.controller

import cn.dev33.satoken.stp.StpUtil
import cn.dev33.satoken.util.SaResult
import io.github.frailty9.crserver.dso.service.ReservationService
import io.github.frailty9.crserver.dto.ResourceBookingParam
import org.noear.solon.annotation.Controller
import org.noear.solon.annotation.Inject
import org.noear.solon.annotation.Mapping
import org.noear.solon.annotation.Path
import org.noear.solon.web.cors.annotation.CrossOrigin

@Suppress("unused")
@CrossOrigin(origins = "*")
@Controller
@Mapping("/api/reservation")
class ReservationController {

    @Inject
    private lateinit var reservationService: ReservationService

    @Mapping("/booking")
    fun booking(rbp: ResourceBookingParam): SaResult {
        val uid = StpUtil.getLoginIdAsLong()
        val reservationId = reservationService.booking(uid, rbp.instanceId, rbp.bookUnit)
        return if (reservationId > 0) SaResult.data(reservationId) else SaResult.error("预约失败")
    }

    @Mapping("/detail/{reservationId}")
    fun detail(@Path reservationId: Long): SaResult {
        val reservation = reservationService.getById(reservationId)
        return if (reservation != null) SaResult.data(reservation) else SaResult.error("预约不存在")
    }

    @Mapping("/cancel")
    fun cancel(reservationId: Long): SaResult {
        val uid = StpUtil.getLoginIdAsLong()
        val cancel = reservationService.cancel(reservationId)
        return if (cancel) SaResult.ok() else SaResult.error("取消失败")
    }

    @Mapping("/my")
    fun my(): SaResult {
        val uid = StpUtil.getLoginIdAsLong()
        val reservations = reservationService.getsByUserId(uid)
        return SaResult.data(reservations)
    }

}
